// mqtt.utils.ts
import * as Paho from 'paho-mqtt';


export class MqttClient {
    private client: Paho.Client | null = null;
    private connected = false;

    // constructor(private options: MqttOptions) { }
    private options = {
        url: import.meta.env.VITE_APP_MQTT_URL,
        clientId: import.meta.env.VITE_APP_CLIENT_ID,
        useSSL: false
    }

    async connect(): Promise<void> {
        console.log('options', this.options)
        this.client = new Paho.Client(this.options.url, this.options.clientId);

        this.client.onConnectionLost = (_responseObject) => {
            this.connected = false;
            console.error('Connection lost:', _responseObject);
        };

        // this.client.onMessageArrived = (message) => {
        //     console.log(`Received message: ${message.payloadString} on topic ${message.destinationName}`);
        // };


        // 订阅主题成功时的回调函数
        this.client.onMessageArrived = (message: any) => {
            console.log("接收到消息: -------------- " + message.payloadString);
            // 处理收到的消息
            // message.value = message.payloadString;
        };
        const connectionOptions: Paho.ConnectionOptions = {
            useSSL: this.options.useSSL ?? false,
            onSuccess: () => {
                this.connected = true;
                console.log('Connected to MQTT broker');
            },
            onFailure: (error) => {
                console.error('Failed to connect:', error);
            },
        };

      
        // await new Promise((resolve, reject) => {
        //     this.client?.connect(connectionOptions, resolve, reject);
        // });
    }




    onMessageArrived(): void {
        if (this.client?.isConnected()) {
            this.client.onMessageArrived = (message: any) => {
                console.log("接收到消息: " + message.payloadString);
                // 处理收到的消息
                return  message.payloadString;
            };

        } else {
            console.log("接不到: ");
        }
    }

    disconnect(): void {
        if (this.client?.isConnected()) {
            this.client.disconnect();
            this.connected = false;
            console.log('Disconnected from MQTT broker');
        }
    }

    publish(topic: string, message: string): void {
        if (this.connected) {
            const mqttMessage = new Paho.Message(message);
            mqttMessage.destinationName = topic;
            this.client?.send(mqttMessage);
            console.log(`Published message: ${message} to topic ${topic}`);
        } else {
            console.warn('Not connected to publish a message');
        }
    }

    subscribe(topic: string): void {
        console.log('subscribe lai le')
        if (this.connected) {
            this.client?.subscribe(topic, { qos: 1 });
            console.log(`Subscribed to topic: ${topic}`);
        } else {
            console.warn('Not connected to subscribe');
        }
    }

    unsubscribe(topic: string): void {
        if (this.connected) {
            this.client?.unsubscribe(topic);
            console.log(`Unsubscribed from topic: ${topic}`);
        } else {
            console.warn('Not connected to unsubscribe');
        }
    }

    // onMessageArrived = (message: any) => {
    //     this.client.onMessageArrived = (message) => {
    //         console.log(`Received message: ${message.payloadString} on topic ${message.destinationName}`);
    //     };
    //     console.log("接收到消息: " + message.payloadString);
    //     // 处理收到的消息
    //     message.value = message.payloadString;
    // };
}